package com.echo.yixiaowu.main

import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.echo.yixiaowu.R
import kotlinx.coroutines.delay
import kotlin.coroutines.cancellation.CancellationException
import kotlin.math.absoluteValue

/**
 * 线性插值函数，用于平滑计算过渡值
 */
fun lerp(start: Float, stop: Float, fraction: Float): Float {
    return (1 - fraction) * start + fraction * stop
}

data class CarouselImageItem(
    val id: Int,
    val title: String,
    @DrawableRes val imageRes: Int
)

@Composable
@Preview
fun CarouselImage(userScrollEnabled: Boolean = false) {
    val imageList = remember {
        listOf(
            CarouselImageItem(1, "Image 1", R.drawable.image2),
            CarouselImageItem(2, "Image 2", R.drawable.image3),
            CarouselImageItem(3, "Image 3", R.drawable.image4),
            CarouselImageItem(4, "Image 3", R.drawable.image5),
            CarouselImageItem(5, "Image 3", R.drawable.image6),
        )
    }
    val pageCount by remember { mutableIntStateOf(Int.MAX_VALUE) }
    val items = imageList.ifEmpty {
        listOf(Color.Red, Color.Green, Color.Blue, Color.Yellow, Color.Magenta)
    }

    // 设置虚拟页面数量，然后通过取模运算映射回真实的图片列表索引
    val pagerState = rememberPagerState(initialPage = pageCount / 2 - 3, // 从中间开始计算，以便可以无限向左和向右滚动
        pageCount = { pageCount })

    Box(
        modifier = Modifier
            .height(200.dp)
    ) {
        // 轮播图
        HorizontalPager(
            state = pagerState,
            contentPadding = PaddingValues(horizontal = 26.dp),
            userScrollEnabled = userScrollEnabled
        ) { virtualPage ->
            val realIndex = virtualPage % items.size
            val pageOffset =
                ((pagerState.currentPage - virtualPage) + pagerState.currentPageOffsetFraction).absoluteValue
            val scale = lerp(
                start = 1f, stop = 0.9f, fraction = pageOffset.coerceIn(0f, 1f)
            )

            Box(modifier = Modifier
                .graphicsLayer {
                    scaleX = scale
                    scaleY = scale
                }
                .fillMaxWidth()
                .clip(RoundedCornerShape(14.dp))) {
                if (items.first() is CarouselImageItem) {
                    Image(
                        painter = painterResource(id = (items[realIndex] as CarouselImageItem).imageRes),
                        contentDescription = "Carousel Image ${realIndex + 1}",
                        contentScale = ContentScale.Crop,
                        modifier = Modifier.fillMaxSize()
                    )
                } else {
                    Box(
                        modifier = Modifier
                            .background(items[realIndex] as Color)
                            .fillMaxSize()
                    )
                }
            }
        }

        // 指示器悬浮在 Pager 之上
        Row(
            Modifier
                .align(Alignment.BottomCenter)
                .padding(bottom = 24.dp)
        ) {
            repeat(items.size) { index ->
                val realCurrentPage = pagerState.currentPage % items.size
                val color = if (pagerState.isScrollInProgress) {
                    Color.Gray.copy(alpha = 0.5f)
                } else {
                    if (index == realCurrentPage) Color.White else Color.Gray.copy(alpha = 0.5f)
                }

                Box(
                    modifier = Modifier
                        .padding(horizontal = 4.dp)
                        .clip(CircleShape)
                        .background(color)
                        .size(8.dp)
                )
            }
        }
    }

    // 自动轮播
    LaunchedEffect(Unit) { // 使用 Unit 作为 key，让协程只启动一次
        while (true) {
            delay(5000)
            if (!pagerState.isScrollInProgress) {
                try {
                    pagerState.animateScrollToPage(
                        page = pagerState.currentPage + 1
                    )
                } catch (e: CancellationException) {
                    // 忽略中断
                }
            } else {
                // 检测到用户操作，延长等待时间
                delay(5000)
            }
        }
    }
}